import { App } from "vue";
import {
  createRouter,
  createWebHistory,
  RouteRecordRaw,
  createWebHashHistory
} from "vue-router";
import { builtinRoutes } from "./builtin";
import { createRouterGuard } from "./guard";
import { useRouterStore } from "@/store/modules/router";

const routes: RouteRecordRaw[] = [...builtinRoutes];

const router = createRouter({
  history:
    import.meta.env.VITE_ROUTER_HISTORY_MODE === "history"
      ? createWebHistory()
      : createWebHashHistory(),
  routes
});

const setupRouter = (app: App) => {
  const routerStore = useRouterStore();
  routerStore.initRoutes();
  [...routerStore.constantRoutes].forEach(route => {
    router.addRoute(route);
  });
  app.use(router);
  createRouterGuard(router);
};

export default setupRouter;
